<template>
  <div id="calendar" style="width: 1000px"></div>
</template>

<script setup lang="ts">
import {
  Calendar,
  EventClickArg,
  EventContentArg,
  EventInput,
} from '@fullcalendar/core'
import daygrid from '@fullcalendar/daygrid'
import interaction, { DateClickArg } from '@fullcalendar/interaction'
import { onMounted, ref, PropType, watch } from 'vue'

let emits = defineEmits(['date-click', 'event-click'])
const props = defineProps({
  // 语音
  local: {
    type: String,
    default: 'zh-cn',
  },
  // 视图模式
  initalView: {
    type: String,
    default: 'dayGridMonth',
  },
  //按钮文字
  buttonText: {
    type: Object,
    default: () => {
      return {
        today: '今天',
        month: '月',
        week: '周',
        day: '天',
        prevYear: '上一年',
        nextYear: '下一年',
        prev: '上一月',
        next: '下一月',
      }
    },
  },
  // 头部工具栏
  headerToolbar: {
    type: Object,
    default: () => {
      return {
        start: 'title',
        center: '',
        end: 'prev today next',
      }
    },
  },
  // 底部工具栏
  footerToolbar: {
    type: Object,
    default: () => {},
  },
  // 事件源
  events: {
    type: Array as PropType<EventInput[]>,
    default: () => [],
  },
  // 日历显示结束时间
  displayEventEnd: {
    type: Boolean,
    default: false,
  },
  eventContent: {
    type: Function,
  },
})
const calendar = ref<Calendar>()
const renderCalendar = () => {
  let el = document.getElementById('calendar')
  if (!el) return
  calendar.value = new Calendar(el, {
    plugins: [daygrid, interaction],
    locale: props.local,
    initialView: props.initalView,
    buttonText: props.buttonText,
    headerToolbar: props.headerToolbar,
    footerToolbar: props.footerToolbar,
    eventSources: [
      {
        events(e, callback) {
          if (props.events?.length) {
            callback(props.events)
          } else {
            callback([])
          }
        },
      },
    ],
    // 点击日历上面某一天
    dateClick(info: DateClickArg) {
      emits('date-click', info)
    },
    eventClick(info: EventClickArg) {
      emits('event-click', info)
    },
    displayEventEnd: props.displayEventEnd,
    eventContent: props.eventContent,
  })
  calendar.value.render()
}

watch(
  () => props.events,
  (val) => {
    renderCalendar()
  },
  { deep: true }
)

onMounted(() => {
  renderCalendar()
})
</script>

<style scoped lang="scss"></style>
